# OBEvolutionAI/CourseControl.py
from mxupy import IM, EntityXControl
import OBEvolutionAI as obe
from playhouse.shortcuts import model_to_dict

class CourseControl(EntityXControl):
    class Meta:
        model_class = obe.Course
        
    def get_list_with_creator(self, where=None, order_by=None, limit=None, offset=None):
        """
        获取课程列表，包含创建者信息
        """
        try:
            # 使用原始SQL查询，包含创建者信息
            # 确保只查询user表中存在的字段：userId和username
            query = """
            SELECT 
                c.*, 
                u.userId as creater__userId,
                u.username as creater__username
            FROM course c
            LEFT JOIN user u ON c.createrId = u.userId
            """
            
            params = []
            if where:
                # 简单处理where条件
                query += " WHERE "
                conditions = []
                for key, value in where.items():
                    conditions.append(f"c.{key} = %s")
                    params.append(value)
                query += " AND ".join(conditions)
                
            if order_by:
                query += f" ORDER BY {order_by}"
                
            if limit:
                query += f" LIMIT {limit}"
                
            if offset:
                query += f" OFFSET {offset}"
            
            # 执行查询
            cursor = self.db.execute_sql(query, params)
            columns = [col[0] for col in cursor.description]
            results = []
            
            for row in cursor.fetchall():
                row_dict = dict(zip(columns, row))
                # 处理创建者信息
                if row_dict.get('creater__userId'):
                    row_dict['creater'] = {
                        'userId': row_dict['creater__userId'],
                        'username': row_dict['creater__username'],
                        # 使用username作为name的值，因为user表中没有name字段
                        'name': row_dict['creater__username']
                    }
                # 删除临时字段
                for key in list(row_dict.keys()):
                    if key.startswith('creater__'):
                        del row_dict[key]
                        
                results.append(row_dict)
            
            return IM(data=results)
        except Exception as e:
            return IM().set_error(f"查询失败: {str(e)}")

# 正确注册自定义方法，确保API可以访问
# 使用 setattr 方式注册方法到类上
setattr(CourseControl, 'get_list_with_creator', CourseControl.get_list_with_creator)